package com.baoli.umpush.common;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

@Slf4j
public class PushClient {

    // The user agent
    private final String USER_AGENT = "Mozilla/5.0";

    // The host
    private static final String host = "http://msg.umeng.com";

    // The upload path
    private static final String uploadPath = "/upload";

    // The post path
    private static final String postPath = "/api/send";


    public String send(UmengNotification msg) throws Exception {
        String timestamp = Integer.toString((int) (System.currentTimeMillis() / 1000));
        String url = host + postPath;
        String reason = null;
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            //设置预定义的键值
            msg.setPredefinedKeyValue("timestamp", timestamp);
            // umeng加密
            String postBody = msg.getPostBody();
            String sign = DigestUtils.md5Hex(("POST" + url + postBody + msg.getAppMasterSecret()).getBytes("utf8"));
            url = url + "?sign=" + sign;

            HttpPost post = new HttpPost(url);
            post.setHeader("User-Agent", USER_AGENT);
            StringEntity se = new StringEntity(postBody, "UTF-8");
            post.setEntity(se);
            // Send the post request and get the response
            CloseableHttpResponse response = client.execute(post);
            int status = response.getStatusLine().getStatusCode();
            if (status == HttpStatus.SC_OK) {
                log.info("Unemg notification sent successfully.");
            } else {
                reason = EntityUtils.toString(response.getEntity(), "utf-8");
                log.error("Umeng push result is {}.", reason);
            }
        }
        return reason;

    }


    public String uploadContents(String appkey, String appMasterSecret, String contents) throws Exception {
        String fileId = null;
        String timestamp = Integer.toString((int) (System.currentTimeMillis() / 1000));
        // Construct the request
        String url = host + uploadPath;
        // Construct the json string
        JSONObject uploadJson = new JSONObject();
        uploadJson.put("appkey", appkey);
        uploadJson.put("timestamp", timestamp);
        uploadJson.put("content", contents);
        String postBody = uploadJson.toString();

        try (CloseableHttpClient client = HttpClients.createDefault()) {
            // 加密
            String sign = DigestUtils.md5Hex(("POST" + url + postBody + appMasterSecret).getBytes("utf8"));
            url = url + "?sign=" + sign;

            HttpPost post = new HttpPost(url);
            post.setHeader("User-Agent", USER_AGENT);
            StringEntity se = new StringEntity(postBody, "UTF-8");
            post.setEntity(se);
            // Send the post request and get the response
            CloseableHttpResponse response = client.execute(post);
            String result = EntityUtils.toString(response.getEntity(), "utf-8");

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // Decode response string and get file_id from it
                JSONObject respJson = JSONObject.parseObject(result);
                String ret = respJson.getString("ret");
                if (!ret.equals("SUCCESS")) {
                    throw new Exception("Failed to upload file");
                }
                JSONObject data = respJson.getJSONObject("data");
                fileId = data.getString("file_id");
            } else {
                log.error("Umeng upload file result is {}.", result);
                throw new Exception("Failed to upload file");
            }

        }

        return fileId;
    }
}
